package com.example.cloudcommon.event.stream;


import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/events")
@CrossOrigin(origins = "*") // 允许跨域
public class EventStreamController {

    @Autowired
    private EventStreamService eventStreamService;

    /**
     * 订阅事件流
     */
    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamEvents(
            @RequestParam(defaultValue = "default") String clientId,
            HttpServletResponse response) {

        // 设置SSE相关响应头
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Connection", "keep-alive");
        response.setCharacterEncoding("UTF-8");

        return eventStreamService.createEmitter(clientId);
    }

    /**
     * 发送消息到特定客户端
     */
    @PostMapping("/send")
    public ResponseEntity<String> sendMessage(
            @RequestParam String clientId,
            @RequestBody Object message) {

        eventStreamService.sendEvent(clientId,
                EventStream.of("custom-message", message));

        return ResponseEntity.ok("消息已发送");
    }

    /**
     * 广播消息到所有客户端
     */
    @PostMapping("/broadcast")
    public ResponseEntity<String> broadcastMessage(@RequestBody Object message) {

        eventStreamService.broadcast(EventStream.of("broadcast", message));

        return ResponseEntity.ok("广播消息已发送");
    }

    /**
     * 关闭连接
     */
    @PostMapping("/close")
    public ResponseEntity<String> closeConnection(@RequestParam String clientId) {

        eventStreamService.closeEmitter(clientId);

        return ResponseEntity.ok("连接已关闭");
    }

    /**
     * 获取活跃连接数
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getStats() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("activeConnections", eventStreamService.getActiveConnections());
        stats.put("timestamp", new Date());
        return ResponseEntity.ok(stats);
    }
}
